<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
//use App\Models\logfile;

class LogfileController extends Controller
{
    protected $name = '登录日志';
    protected $find = ['id', 'Ip', 'Loginuserid', 'Loginuser', 'Logintime', 'Logouttime', 'timeoutcount'];
    /**
     * 查询
     */
    public function find(Request $request)
    {
        try {
            $param = json_decode($request->param, true);

            $Loginuserid = $this->I($param['Loginuserid'] ?? null);
            $Loginuser = $this->I($param['Loginuser'] ?? null);
            $Loginbegin = $this->I($param['loginbegin'] ?? null);
            $Loginend = $this->I($param['loginend'] ?? null);
            $state = $this->I($param['state'] ?? null);
            $page = intval($this->I($param['page'] ?? 1));
            $pagecount = intval($this->I($param['pagecount'] ?? 50));
            $where = ' a.isdel=0 ';
            if (!empty($Loginuserid)) {
                $where .= " and a.Loginuserid = '$Loginuserid' ";
            }
            if (!empty($Loginuser)) {
                $where .= " and a.Loginuser = '$Loginuser' ";
            }
            if (!empty($Loginbegin)) {
                $where .= " and a.Logintime >= '$Loginbegin' ";
            }
            if (!empty($Loginend)) {
                $where .= " and a.Logintime < '$Loginend 23:59:59' ";
            }
            if (is_numeric($state)) {
                $d = 'f';
                if (intval($state) == 0) {
                    $where .= " and  (DATE_ADD(a.Logintime, INTERVAL timeoutcount SECOND)< now() || a.Logouttime is not null)";
                }
                if ($state == '1') {
                    $where .= " and  (DATE_ADD(a.Logintime, INTERVAL timeoutcount SECOND)> now() && a.Logouttime is  null)";
                }
            }
            $temp = DB::table('logfile as a')
                ->select($this->find)
                ->whereRaw($where)
                ->orderBy('a.Logintime', 'desc')
                ->paginate($pagecount, ['id'], 'page', $page)
                ->toArray(); // 控制页码，默认每页 10 条
            $res = $temp['data'];
            $allcount = $temp['total'];
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'count' => $allcount, 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }

}
